package jupitermouse.site.java;

import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.java.ExecutionEnvironment;
import org.apache.flink.api.java.operators.DataSource;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.util.Collector;

import java.util.stream.Stream;

public class BatchWCJavaApp {

    public static void main(String[] args) throws Exception {

        //文件路径
        String inputPath = "file:///E:\\workroom\\hdsp\\flink_demo\\resource\\wordcount\\word.txt";

        //获取环境变量
        final ExecutionEnvironment env = ExecutionEnvironment.getExecutionEnvironment();

        //读取数据源
        DataSource<String> dataSource = env.readTextFile(inputPath);

        //转换
        dataSource.flatMap(new FlatMapFunction<String, Tuple2<String, Long>>() {
            @Override
            public void flatMap(String value, Collector<Tuple2<String, Long>> out) throws Exception {
                String[] values = value.toLowerCase().split(" ");
                Stream.of(values)
                        .forEach(
                                i -> {
                                    out.collect(new Tuple2<>(i, 1L));
                                }
                        );
            }
        }).groupBy(0)
                .sum(1)
                .print();

//        env.execute("BatchWCJavaApp");

    }
}
